import { useEffect, useRef, useState } from 'react';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { PageContainer, ProColumns, ProTable,ModalForm,ProFormText, ActionType,ProForm, ProFormTextArea, ProFormDigit } from '@ant-design/pro-components';
import { Button, Popconfirm, Space } from 'antd';
import { loadDataAPI,addOneAPI, loadOneByIdAPI, modifyByIdAPI, deleteByIdAPI, deleteManyByIds } from '@/services/mlists-list';
import { dalImg } from '@/utils/tools';
import MyUpload from '@/components/MyUpload';
import MyEditor from '@/components/MyEditor';

function WorkList() {
  const [isShow,setIsShow] = useState(false)
  const actionRef = useRef<ActionType>();
  const [currentId,setCurrentId] = useState('');//记录当前id，用于区分是新增还是修改
  const [myForm] = ProForm.useForm()//获取表单

  const [imageUrl,setImageUrl] = useState("")
  const [html,setHtml] = useState('')

  //选中的行id
  const [selRows,setSelRows] = useState<any>([])

  useEffect(()=>{
    //关闭窗口之后重置数据
    if(!isShow){
      setCurrentId("")
      setImageUrl("")
      setHtml("")
    }
  },[isShow])
  const columns:ProColumns[] = [
    {
      title:"序号",
      align:'center',
      hideInSearch:true,
      render(c,r,i){
        return i+1;
      }
    },{
      title:"名字",
      dataIndex:"name"
    },{
      title:"价格",
      align:'center',
      dataIndex:"price"
    },{
      title:"数量",
      align:'center',
      dataIndex:"amount"
    },{
      title:"主图",
      hideInSearch:true,
      render(v:any){
        return <img className='t-img' src={dalImg(v.image)} alt="" />
      }
    },{
      title:"分类",
      render(v:any){
        return v.category?.name
      }
    },{
      title:"描述",
      hideInSearch:true,
      dataIndex:"desc",
      ellipsis:true
    },
    
    {
      title:"操作",
      hideInSearch:true,
      render(v:{id:string}){
        return (
          <Space>
            <Button icon={<EditOutlined />} type="primary" size='small'
            onClick={async ()=>{
              //获取数据
              const info = await loadOneByIdAPI(v.id)
              //填充表单
              myForm.setFieldsValue(info.data);
              setImageUrl(info.data.image)
              setHtml(info.data.content)
              setIsShow(true)
              setCurrentId(v.id)
            }}
            />
            <Popconfirm title="是否确认删除"
              onConfirm={async ()=>{
                deleteByIdAPI(v.id)
                actionRef.current?.reload()
              }}
            >
            <Button icon={<DeleteOutlined />} type='primary' size="small" danger />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  // const data = []
  return (
    <PageContainer>
      <ProTable
      rowKey="id"
      rowSelection={{
        selectedRowKeys:selRows,//设置当前选中的
        onChange(selectedRowKeys){
          console.log(selectedRowKeys);
          setSelRows(selectedRowKeys)
        }
      }}
      //这个属性可以直接操作表格中的各种方法
      actionRef={actionRef}
      columns={columns}
      request={loadDataAPI}
      // dataSource={data}
      toolBarRender={()=> {
        //操作按钮数据，默认只有一个新增按钮
        const tools = [
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            key={1} 
            onClick={()=>{
              setIsShow(true);
            }} 
            />,
          ];
          //如果勾选了指定的行，显示多行删除按钮
          if(selRows.length>0){
            tools.push(
              <Button type='primary' danger key={2}
              onClick={async()=>{
                //通过join拼接数组
                await deleteManyByIds(selRows.join(","));
                actionRef.current?.reload();//删除之后重新加载数据
                setSelRows([])//清空选中的值
              }}
              >
              批量删除
              </Button>,
            )
          }
          return tools;
        }}
        />
      <ModalForm
      form = {myForm}
      title="编辑" open={isShow}
      //open状态改变
      onOpenChange={setIsShow} 
      //表示模态框的属性
      modalProps={{maskClosable:false,//点击遮罩层的时候不关闭
                  destroyOnClose:true//关闭之后销毁内容
                }} 
      onFinish={async (v)=>{
        // console.log(v);
        //提交的时候执行
        if(currentId){
          await modifyByIdAPI(currentId,{...v,image:imageUrl,content:html})//当前id存在则是修改
        } else {
          await addOneAPI({...v,image:imageUrl,content:html})//否则是新增
        }
        setIsShow(false);
        actionRef.current?.reload()//重新加载数据
      }}
      >
        <ProFormText
        label="名字"
        placeholder="请输入名字"
        name='name'
        rules={[
          {
            required:true,
            message:"名字不能为空"
          }
        ]}
        ></ProFormText>
        <ProForm.Item label="主图">
          <MyUpload imageUrl={imageUrl} setImageUrl={setImageUrl} />
        </ProForm.Item>
        <ProFormTextArea label="简介" placeholder="请输入简介" name="desc" />
        <ProFormDigit label="价格" placeholder="请输入价格" name="price" />
        <ProFormDigit label="数量" placeholder="请输入数量" name="amount" />
        {/* <ProFormTextArea label="地址" placeholder="请输入地址" name="address" /> */}
        <ProForm.Item label="详情">
          <MyEditor html={html} setHtml={setHtml} />
        </ProForm.Item>
        
      </ModalForm>
    </PageContainer>
  );
}

export default WorkList;
